package com.jdbc.util;
import com.sun.org.apache.bcel.internal.generic.RETURN;

import javax.servlet.jsp.tagext.TryCatchFinally;
import java.io.Closeable;
import java.io.IOException;
import java.sql.*;
import java.util.ResourceBundle;

public class DButil {
    Connection conn = null;
    Statement stat = null;
    PreparedStatement pstat = null;
    ResultSet rs =null;

    /**
     * 得到连接
     */
    public Connection getConn(){
        try {
            /**
             * 加载驱动
             */
            Class.forName("com.mysql.jdbc.Driver");
            /**
             * 建立连接
             */
            conn = DriverManager.getConnection("jdbc:mysql://www.xiaotao2333.top:3306/selectCourse","xiaotao","mojintao233");
        } catch(ClassNotFoundException e){

            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }catch(IllegalAccessError e){
            e.printStackTrace();
        }
        return conn;
    }

    //释放资源
    public void release() {
        try {
            if (conn != null) {
                conn.close();
            }
            if (rs != null) {
                rs.close();
            }
            if (stat!=null){
                stat.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //查询
    public ResultSet getResultSet(String sql,String []args){
        rs=null;
        if(conn == null){
            conn=this.getConn();
        }

        try {
            pstat=conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                pstat.setString(i+1,args[i]);//参数从1开始
            }

            rs=pstat.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public ResultSet getResultSet(String sql) {
        rs=null;
        if(conn == null){
            conn = this.getConn();
        }
        try {
            stat= conn.createStatement();
            rs=stat.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }



}
